package com.api.gateway.filter;

import com.api.gateway.utils.PassURLUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * @author Howl-Xu
 * @version 1.0.0
 * @Description: 请描述一下这个类文件吧
 * @createTime 2020年03月14日 16:23:00
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = exchange.getRequest().getURI();
        String path = uri.getPath();

        //如果path满足条件，就放行
        if(PassURLUtils.canURLPass(uri.getPath())){
            return chain.filter(exchange);
        }


        String token = request.getQueryParams().getFirst("token");

        //拿到token进行校验，如果Token不通过，抛出异常，如果token通过，放行
        if(token==null){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
